package uia.alumni.useradm;

import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Page;



/**
 * Output a form for changing user data.
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class EditUser extends Page implements Constants {

    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "admin.edituser";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public EditUser() {
        super(Role.admin);
    }


    /**
     * Write a form for editing user data. If the paraameter UID
     * contains a valid user id the form is populated with data
     * for that user. Otherwise the form will be empty, so a new
     * user can be created.
     * @param out
     * @param request
     */
    public void writeBody(PrintWriter out, HttpServletRequest request) {
        long uid = parseLong(request.getParameter(UID), -1);
        String userName = "";
        String password = "";
        boolean locked = false;
        User user = null;

        if (uid >= 0) {
            EntityManager em = emf.createEntityManager();
            user = em.find(User.class, uid);
        }

        if (user == null) {
            out.println("<h1>New user</h1>");
        }
        else {
            userName = user.getUserName();
            out.println("<h1>Edit user: "+userName+"</h1>");
            password = user.getPassword();
            locked = user.isLocked();
        }

        printStartForm(out, SaveUser.SERVLET_NAME);
        if (user != null) out.println("<input type=\"hidden\" name=\""
                +UID+"\" value=\""+uid+"\"/>");
        out.println("<table>");
        printTextField(out, "Username", USERNAME, userName, true);
        printTextField(out, "Password", PASSWORD, password, true);
        printCheckBox(out, "Locked", LOCKED, locked);
        out.println("</table>");
        out.println("<input type=\"submit\" value=\"Save User\"/>");
        out.println("</form>");

        out.print("<p>Roles:");
        if (user != null) {
            for (Role r : user.getRoles()) {
                out.print(" "+r);
            }
        }

        printStartForm(out, UserAdmin.SERVLET_NAME);
        out.println("<input type=\"submit\" value=\"Cancel\"/>");
        out.println("</form>");
    }

    public final static long serialVersionUID = 1;

}
